/* eslint no-unused-vars:0 */
/**
 *
 * @authors Your tyq
 * @date    2019-04-11 21:14:01
 * @version $Id$
 */
import React from 'react';
import 'antd/dist/antd.css';
import './index.less';
import {
    Input,
    Icon,
    Row,
    Col,
    Table,
    Button,
    Modal,
    Checkbox,
    Form,
    DatePicker,
    Radio,
    Select,
    message
} from 'antd';
import { Link } from 'react-router-dom';
import AvancedSearch from '@components/Drawer';
import PubSub from 'pubsub-js';
import Chart from '@components/Chart';
import FolderModal from '@components/FolderModal';
const ButtonGroup = Button.Group;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const Search = Input.Search;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

class SituationPage extends React.Component {
    componentWillReceiveProps(nextProps) {
        this.setState({
            url: nextProps.url,
            parentId: nextProps.typeId,
            mineType: nextProps.mineType,
            isDisabledRead: false
        });
    }

    getList(
        allKeywords = this.state.keyword,
        anyKeyword = this.state.anyKeyword,
        notContainKeywords = this.state.notContainKeywords,
        sourceId = this.state.selectedSourceId,
        startDate = this.state.startDate,
        endDate = this.state.endDate,
        sort = this.state.sort,
        typeId = this.state.selectedTypeId,
        pageNum = this.state.currentPage,
        mineType = this.state.mineType,
        id = this.state.sourceId
    ) {
        this.$post(this.state.url, {
            parentId: this.state.parentId,
            typeId: typeId,
            infoSource: id,
            allKeywords: allKeywords,
            anyKeyword: anyKeyword,
            notContainKeywords: notContainKeywords,
            startDate: startDate,
            endDate: endDate,
            sort: sort,
            pageNum: pageNum,
            mineType: mineType
        })
            .then((res) => {
                if (res) {
                    let data = res.content;
                    let expandedRowKeys = [];
                    for (var i = 0; i < data.length; i++) {
                        data[i]['key'] = data[i].id;
                        expandedRowKeys[i] = data[i].id;
                    }
                    // console.log(res.maxCount);
                    this.setState(
                        {
                            contentList: data,
                            total: res.maxCount,
                            expandedRowKeys: expandedRowKeys
                        },
                        () => {
                            // console.log(this.state.total);
                        }
                    );
                    // console.log(this.state.total);
                    this.forceUpdate();
                }
            })
            .catch((e) => {
                console.log(e);
            });
    }

    //获取下拉框--风险类型数据
    getChildTypeId() {
        this.$get('/trends/menu/menuTreeList', {
            parentId: this.state.parentId
        })
            .then((res) => {
                if (res) {
                    this.setState({
                        childTypeId: res.menuTreeList
                    });
                }
            })
            .catch((e) => {
                console.log(e);
            });
    }

    getHotKeywords() {
        this.$post('trends/topSearch/get')
            .then((res) => {
                this.setState({
                    hotKeywords: res.topKeywords ? res.topKeywords : []
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }

    componentDidMount() {
        let element = document.getElementById('showByparentId');
        /*let theChart = document.getElementById('showChart');
        theChart.style.display =
            this.state.contentList.length == '0' ? 'none' : 'inline';*/
        element.style.display = this.state.parentId == '' ? 'none' : 'inline';
        let readBtn = document.getElementById('showBtnByparentId');
        readBtn.style.display = this.state.parentId == '' ? 'inline' : 'none';
        this.getChildTypeId();
        this.getHotKeywords();
        this.getList();
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.pubsub_messageNum);
    }

    rowSelection = {
        // selectedRowKeys:this.state.selectRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            this.setState({
                selectedRowKeys: selectedRowKeys
            });
        }
    };

    showDrawer = () => {
        this.setState({
            drawer_visible: true
        });
    };

    //点击普通搜索按钮
    onSearch = (value) => {
        this.state.keyword = value;
        this.state.currentPage = 1;
        this.getList();
    };

    //页码变化时调用的函数
    changePage = (page) => {
        this.setState(
            {
                currentPage: page
            },
            () => {
                this.getList();
            }
        );
    };

    handleOk = () => {
        this.setState({
            ModalText: 'The modal will be closed after two seconds',
            confirmLoading: true
        });
        setTimeout(() => {
            this.setState({
                visible: false,
                confirmLoading: false
            });
        }, 2000);
    };
    handleOpen = (expandedRowKeys) => {
        console.log('open');
        this.setState({
            expandedRowKeys: [1, 2, 3] ? expandedRowKeys : []
        });
    };
    handleCancel = () => {
        console.log('Clicked cancel button');
        this.setState({
            visible: false
        });
    };

    handleAdd = () => {
        console.log('addReport');
        this.setState({
            modal_visible: true
        });
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, fieldsValue) => {
            if (err) {
                return;
            }

            // Should format date value before submit.
            const rangeValue = fieldsValue['range-picker'];
            const values = {
                ...fieldsValue,
                'range-picker': [
                    rangeValue[0].format('YYYY-MM-DD'),
                    rangeValue[1].format('YYYY-MM-DD')
                ]
            };
            console.log('Received values of form: ', values);
        });
    };

    onAdvancedSearch(
        all_key,
        each_key,
        none_key,
        source,
        startDate,
        endDate,
        sort
    ) {
        this.setState(
            {
                keyword: all_key,
                anyKeyword: each_key,
                notContainKeywords: none_key,
                sourceId: source,
                startDate: startDate,
                endDate: endDate,
                sort: sort,
                currentPage: 1,
                infoSource: source
            },
            () => {
                this.getList();
            }
        );
    }

    selectHotKeyword(str) {
        this.setState(
            {
                keyword: str,
                currentPage: 1
            },
            () => {
                this.getList();
            }
        );
    }

    download() {
        localStorage.setItem('idList', this.state.selectedRowKeys);
        this.props.history.push(
            '/admin/OurSchoolSituation/PoliticalRisks/Download'
        );
    }

    onchangeType(e) {
        this.setState(
            {
                selectedTypeId: e ? e.key : '',
                currentPage: 1
            },
            () => {
                this.getList();
            }
        );
    }
    onchangeSource(e) {
        this.setState(
            {
                selectedSourceId: e ? e.key : '',
                currentPage: 1
            },
            () => {
                this.getList();
            }
        );
    }

    handleRead = () => {
        this.$post('/trends/unread/readAllUnread').then((res) => {
            this.setState({
                isDisabledRead: true
            });
            PubSub.publishSync('PubSubMessageNum', 0);
        });
    };

    handleReadOne(contentId) {
        this.$post('trends/unread/read', { contentId: contentId })
            .then((res) => {
                if (res.event == 21) {
                    message.success('该动态已读！');
                } else if (res.code == 0) {
                    this.$post('/trends/unread/amount').then((response) => {
                        let temp = 0;
                        if (JSON.stringify(response.amountMap) != '{}') {
                            temp = Object.values(response.amountMap).reduce(
                                (a, b) => a + b
                            );
                        }
                        PubSub.publishSync('PubSubMessageNum', temp);
                    });
                    message.success('标注成功！');
                }
            })
            .catch((e) => {
                message.error('失败');
            });
    }

    onCloseSeniorSearch(drawer_visible) {
        this.setState({
            drawer_visible: drawer_visible
        });
    }
    //获取日期字符串
    getDateStr(count) {
        var dd = new Date();
        dd.setDate(dd.getDate() + count);
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;
        var d = dd.getDate();
        var str = y + '-' + m + '-' + d;
        return str;
    }
    selectDate(type) {
        let startDate;
        let endDate = new Date(this.getDateStr(0) + ' 23:59:59').getTime();
        switch (type) {
            case 'today':
                startDate = new Date(
                    this.getDateStr(0) + ' 00:00:00'
                ).getTime();
                break;
            case 'yesterday':
                startDate = new Date(
                    this.getDateStr(-1) + ' 00:00:00'
                ).getTime();
                break;
            case 'threeDay':
                startDate = new Date(
                    this.getDateStr(-2) + ' 00:00:00'
                ).getTime();
                break;
        }
        this.setState(
            {
                startDate: startDate,
                endDate: endDate,
                currentPage: 1
            },
            () => {
                this.getList();
                this.selectedRowsBySearch();
            }
        );
    }

    selectedRowsBySearch = (
        allKeywords = this.state.keyword,
        anyKeyword = this.state.anyKeyword,
        notContainKeywords = this.state.notContainKeywords,
        sourceId = this.state.selectedSourceId,
        startDate = this.state.startDate,
        endDate = this.state.endDate,
        sort = this.state.sort,
        typeId = this.state.selectedTypeId,
        pageNum = this.state.currentPage,
        mineType = this.state.mineType,
        id = this.state.sourceId
    ) => {
        this.$post('/workBriefing/getSearchId', {
            parentId: this.state.parentId,
            typeId: typeId,
            infoSource: id,
            allKeywords: allKeywords,
            anyKeyword: anyKeyword,
            notContainKeywords: notContainKeywords,
            startDate: startDate,
            endDate: endDate,
            sort: sort,
            pageNum: pageNum,
            mineType: mineType
        })
            .then((res) => {
                if (res) {
                    this.setState({
                        selectedRowKeys: res.obj
                    });
                }
            })
            .catch((e) => {
                console.log(e);
            });
    };

    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {},
                {
                    title: '',
                    dataIndex: 'title',
                    render: (text, record) => {
                        return (
                            <div>
                                <a
                                    href={record.url}
                                    target="_Blank"
                                    rel="noopener noreferrer">
                                    {record.title}
                                </a>
                            </div>
                        );
                    }
                }
            ],

            ModalText: 'Content of the modal',
            visible: false,
            drawer_visible: false,
            modal_visible: false,
            confirmLoading: false,

            contentList: [],
            total: 0,
            startDate: '',
            endDate: '',
            selectedRowKeys: [],

            childTypeId: [],
            selectedTypeId: '',
            selectedSourceId: '',
            keyword: '',
            anyKeyword: '',
            notContainKeywords: '',
            sort: 0,
            currentPage: 1,
            //共用变量
            url: this.props.url,
            parentId: this.props.typeId,
            mineType: this.props.mineType,
            hotKeywords: [],
            //默认展开结点
            expandedRowKeys: []
        };
    }
    workBriefing = () => {
        if (this.state.selectedRowKeys.length == 0) {
            message.error('请先选择导入的数据！');
            return;
        }

        this.$post('/workBriefing/createWord', {
            keyWords: this.state.keyWords
                ? this.state.keyWords
                : '21周中大调课事件',
            idList: this.state.selectedRowKeys
        })
            .then((res) => {
                // 组装a标签
                let elink = document.createElement('a');

                // // 设置下载文件名
                elink.href = res;
                elink.target = '_Blank';

                elink.style.display = 'none';
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            })
            .catch((e) => {
                console.log(e);
            });
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const { visible, confirmLoading, ModalText } = this.state;
        const formItemLayout = {
            labelCol: {
                xs: 24,
                sm: 9
            },
            wrapperCol: {
                xs: 24,
                sm: 16
            }
        };

        const offsetLayout = {
            wrapperCol: {
                xs: 24,
                sm: {
                    span: 12,
                    offset: 4
                }
            }
        };
        const test = true;

        const { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.rowSelection
        };

        return (
            <div>
                <Col span="17">
                    <Row>
                        <Col span="14">
                            <h3 style={{ marginTop: '20px' }}>
                                全部风险:&nbsp;(共{this.state.total}条/已选中
                                {this.state.selectedRowKeys.length}条)
                            </h3>
                            <Button type="primary" onClick={this.workBriefing}>
                                确立舆情
                            </Button>
                            <div id="showByparentId">
                                <Select
                                    className="sub-row2-select"
                                    labelInValue
                                    defaultValue={{ key: '请选择风险类型' }}
                                    style={{ width: 150, height: 30 }}
                                    onChange={this.onchangeType.bind(this)}
                                    allowClear>
                                    {this.state.childTypeId.map((item) => {
                                        return (
                                            <Option
                                                key={item.id}
                                                value={item.id}>
                                                {item.name}
                                            </Option>
                                        );
                                    })}
                                </Select>
                            </div>
                        </Col>
                        <Col span="10">
                            <Button
                                className="advanced-search"
                                type="primary"
                                onClick={this.showDrawer}
                                style={{ float: 'right' }}>
                                高级搜索
                            </Button>
                            <Search
                                placeholder="关键词"
                                onSearch={(value) => this.onSearch(value)}
                                style={{
                                    width: 200,
                                    float: 'right',
                                    marginTop: '20px'
                                }}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <div className="buttonPanel">
                                <Button
                                    onClick={this.selectDate.bind(
                                        this,
                                        'today'
                                    )}>
                                    今天
                                </Button>
                                <Button
                                    onClick={this.selectDate.bind(
                                        this,
                                        'yesterday'
                                    )}>
                                    昨天
                                </Button>
                                <Button
                                    onClick={this.selectDate.bind(
                                        this,
                                        'threeDay'
                                    )}>
                                    近三天
                                </Button>
                                <Button
                                    id="showBtnByparentId"
                                    type="primary"
                                    onClick={this.handleRead}>
                                    全部已读
                                </Button>
                            </div>
                        </Col>
                    </Row>
                    <Row style={{ marginTop: '20px' }}>
                        {this.state.contentList &&
                        this.state.contentList.length ? (
                            <Table
                                showHeader={false}
                                columns={this.state.columns}
                                expandedRowRender={(record) => (
                                    <div
                                        style={{
                                            marginLeft: '62px'
                                        }}>
                                        <Row>
                                            <Col span="4">
                                                <span>信息源：</span>
                                                {record.infoSource}
                                            </Col>
                                            <Col span="9">
                                                <span>发布时间：</span>
                                                {this.$changeTimeToString(
                                                    record.createTime
                                                )}
                                            </Col>
                                            <Col span="11">
                                                <span>作者：</span>
                                                {record.author}
                                            </Col>
                                        </Row>
                                        <br />
                                        <Row>
                                            <p>{record.text}</p>
                                        </Row>
                                        <Row>
                                            <div className="btnPanel">
                                                <Col span="3">
                                                    <Button>
                                                        <Icon
                                                            type="up-circle"
                                                            theme="filled"
                                                        />
                                                        置顶
                                                    </Button>
                                                </Col>
                                                <Col span="4">
                                                    <Button>
                                                        <Icon
                                                            type="star"
                                                            theme="filled"
                                                        />
                                                        加入简报
                                                    </Button>
                                                </Col>
                                                <Col span="4">
                                                    <Button
                                                        onClick={this.handleReadOne.bind(
                                                            this,
                                                            record.id
                                                        )}>
                                                        <Icon
                                                            type="eye"
                                                            theme="filled"
                                                        />
                                                        标为已读
                                                    </Button>
                                                </Col>
                                            </div>
                                        </Row>
                                    </div>
                                )}
                                dataSource={this.state.contentList}
                                rowSelection={rowSelection}
                                pagination={{
                                    current: this.state.currentPage,
                                    total: this.state.total,
                                    onChange: this.changePage
                                }}
                                onExpand={(expanded, record) => {
                                    let expandedRowKeys = this.state
                                        .expandedRowKeys;
                                    if (!expanded) {
                                        expandedRowKeys.splice(
                                            expandedRowKeys.indexOf(record.key),
                                            1
                                        );
                                    } else {
                                        let expandedRowKeys = this.state
                                            .expandedRowKeys;
                                        expandedRowKeys.splice(
                                            expandedRowKeys.indexOf(record.key),
                                            0,
                                            record.key
                                        );
                                    }
                                    this.setState(expandedRowKeys);
                                }}
                                expandedRowKeys={this.state.expandedRowKeys}
                            />
                        ) : (
                            ' '
                        )}
                    </Row>
                </Col>
                <Col span="6" style={{ float: 'right' }}>
                    <Row>
                        <div style={{ marginTop: '20px' }}>
                            {this.state.contentList &&
                            this.state.contentList.length ? (
                                <div>
                                    <ButtonGroup className=" hotKeywordBtnPanel">
                                        {this.state.hotKeywords.map((item) => (
                                            <Button
                                                className=" hotKeywordBtn"
                                                type="primary"
                                                onClick={this.selectHotKeyword.bind(
                                                    this,
                                                    item
                                                )}>
                                                {item}
                                            </Button>
                                        ))}
                                    </ButtonGroup>
                                    <Chart id="showChart" />
                                </div>
                            ) : (
                                ''
                            )}
                        </div>
                    </Row>
                </Col>
                <AvancedSearch
                    drawer_visible={this.state.drawer_visible}
                    onAdvancedSearch={this.onAdvancedSearch.bind(this)}
                    onClose={this.onCloseSeniorSearch.bind(this)}
                />
                <FolderModal modal_visible={this.state.modal_visible} />
            </div>
        );
    }
}
export default Form.create()(SituationPage);
